<!-- eslint-disable -->
<template>
	<view class="player-wrapper" :id="videoWrapperId" :parentId="id" :randomNum="randomNum"
		:change:randomNum="domVideoPlayer.randomNumChange" :viewportProps="viewportProps"
		:change:viewportProps="domVideoPlayer.viewportChange" :videoSrc="videoSrc"
		:change:videoSrc="domVideoPlayer.initVideoPlayer" :command="eventCommand"
		:change:command="domVideoPlayer.triggerCommand" :func="renderFunc" :change:func="domVideoPlayer.triggerFunc">
		<!-- 加载指示器 -->
		<view class="custom-loading-overlay" :class="{ 'is-hidden': !showLoading }">
			<view class="custom-loading-spinner"></view>
		</view>
		<!-- 视频元素将由 renderjs 动态插入 -->
	</view>
</template>

<script>
	// 设备性能检测工具
	const DevicePerformanceTier = {
		detectTier() {
			const systemInfo = uni.getSystemInfoSync();
			const { windowWidth, windowHeight, system, model, platform } = systemInfo;
			
			// 根据设备型号和内存判断性能等级
			const isLowEnd = this.isLowEndDevice(model, system);
			const isHighEnd = this.isHighEndDevice(model, system);
			
			if (isLowEnd) return 'low';
			if (isHighEnd) return 'high';
			return 'medium';
		},
		
		isLowEndDevice(model, system) {
			// 低端设备判断逻辑
			const lowEndKeywords = [
				'redmi', '小米', '荣耀', 'honor', 'oppo a', 'vivo y', '华为畅享',
				'meizu', '魅族', 'realme', '三星a', 'galaxy a'
			];
			const modelLower = model.toLowerCase();
			return lowEndKeywords.some(keyword => modelLower.includes(keyword));
		},
		
		isHighEndDevice(model, system) {
			// 高端设备判断逻辑
			const highEndKeywords = [
				'iphone 1', 'iphone 2', '小米1', '小米2', '华为mate', '华为p',
				'oppo find', 'vivo x', '三星s', 'galaxy s', 'oneplus'
			];
			const modelLower = model.toLowerCase();
			return highEndKeywords.some(keyword => modelLower.includes(keyword));
		},
		
		getOptimizationConfig(tier) {
			const configs = {
				low: {
					preload: 'metadata',
					autoplay: false,
					preloadCount: 1,
					enableHardwareAcceleration: true,
					disableVisualEffects: true,
					quality: '540p'
				},
				medium: {
					preload: 'auto',
					autoplay: true,
					preloadCount: 2,
					enableHardwareAcceleration: true,
					disableVisualEffects: false,
					quality: '720p'
				},
				high: {
					preload: 'auto',
					autoplay: true,
					preloadCount: 3,
					enableHardwareAcceleration: true,
					disableVisualEffects: false,
					quality: '1080p'
				}
			};
			return configs[tier] || configs.medium;
		}
	};

	// CDN 选择器
	class CDNSelector {
		constructor() {
			this.cdnNodes = [
				{ url: 'https://cdn1.douyin.com', latency: 0, successRate: 0 },
				{ url: 'https://cdn2.douyin.com', latency: 0, successRate: 0 },
				{ url: 'https://cdn3.douyin.com', latency: 0, successRate: 0 }
			];
		}
		
		async selectBestCDN(videoUrl) {
			// 简单的 CDN 选择逻辑，实际项目应该更复杂
			const randomIndex = Math.floor(Math.random() * this.cdnNodes.length);
			return this.cdnNodes[randomIndex].url;
		}
	}

	export default {
		props: {
			src: {
				type: String,
				default: ''
			},
			autoplay: {
				type: Boolean,
				default: false
			},
			loop: {
				type: Boolean,
				default: false
			},
			controls: {
				type: Boolean,
				default: false
			},
			objectFit: {
				type: String,
				default: 'contain'
			},
			muted: {
				type: Boolean,
				default: false
			},
			playbackRate: {
				type: Number,
				default: 1
			},
			isLoading: {
				type: Boolean,
				default: false
			},
			poster: {
				type: String,
				default: ''
			},
			id: {
				type: String,
				default: ''
			},
			// 新增：性能优化相关props
			preloadStrategy: {
				type: String,
				default: 'auto' // 'none', 'metadata', 'auto'
			},
			enableAdaptiveBitrate: {
				type: Boolean,
				default: true
			},
			maxBufferSize: {
				type: Number,
				default: 30 // 秒
			}
		},
		data() {
			return {
				randomNum: Math.floor(Math.random() * 100000000),
				videoSrc: '',
				eventCommand: null,
				renderFunc: {
					name: null,
					params: null
				},
				currentTime: 0,
				duration: 0,
				playing: false,
				showLoading: true,
				// 新增：性能优化相关数据
				deviceTier: 'medium',
				optimizationConfig: {},
				cdnSelector: new CDNSelector(),
				networkSpeed: 0,
				videoQuality: 'auto'
			}
		},
		computed: {
			videoWrapperId() {
				return `video-wrapper-${this.randomNum}`
			},
			viewportProps() {
				return {
					autoplay: this.autoplay,
					muted: this.muted,
					controls: this.controls,
					loop: this.loop,
					objectFit: this.objectFit,
					poster: this.poster,
					isLoading: this.isLoading,
					playbackRate: this.playbackRate,
					// 新增性能优化参数
					deviceTier: this.deviceTier,
					optimizationConfig: this.optimizationConfig,
					preloadStrategy: this.preloadStrategy,
					enableAdaptiveBitrate: this.enableAdaptiveBitrate,
					maxBufferSize: this.maxBufferSize
				}
			}
		},
		watch: {
			src: {
				handler(val) {
					setTimeout(() => {
						this.videoSrc = val
					}, 0)
				},
				immediate: true
			},
			isLoading: {
				handler(val) {
					this.showLoading = val;
				},
				immediate: true
			}
		},
		created() {
			// 初始化设备性能检测
			this.detectDevicePerformance();
		},
		methods: {
			// 设备性能检测
			detectDevicePerformance() {
				this.deviceTier = DevicePerformanceTier.detectTier();
				this.optimizationConfig = DevicePerformanceTier.getOptimizationConfig(this.deviceTier);
				console.log(`设备性能等级: ${this.deviceTier}`, this.optimizationConfig);
			},
			
			// 网络状态检测
			async detectNetworkSpeed() {
				if (typeof uni.getNetworkType === 'function') {
					try {
						const networkType = await new Promise((resolve, reject) => {
							uni.getNetworkType({
								success: resolve,
								fail: reject
							});
						});
						this.networkSpeed = this.calculateNetworkScore(networkType.networkType);
					} catch (error) {
						console.warn('网络检测失败:', error);
						this.networkSpeed = 50; // 默认值
					}
				}
			},
			
			calculateNetworkScore(networkType) {
				const scores = {
					'wifi': 100,
					'4g': 80,
					'3g': 60,
					'2g': 30,
					'unknown': 50,
					'none': 0
				};
				return scores[networkType] || 50;
			},
			
			// 智能选择视频质量
			selectVideoQuality() {
				const networkScore = this.networkSpeed;
				const deviceScore = this.deviceTier === 'high' ? 100 : this.deviceTier === 'medium' ? 70 : 40;
				const totalScore = networkScore * 0.6 + deviceScore * 0.4;
				
				if (totalScore > 80) return '1080p';
				else if (totalScore > 60) return '720p';
				else if (totalScore > 40) return '540p';
				else return '360p';
			},
			
			eventEmit({
				event,
				data
			}) {
				this.$emit(event, data);
				if (event === 'fullscreenchange' && data === false) {
					this.$emit('videoDidExitFullScreen');
				}
			},
			
			setViewData({
				key,
				value
			}) {
				key && this.$set(this, key, value)
			},
			
			resetEventCommand() {
				this.eventCommand = null
			},
			
			play() {
				this.eventCommand = 'play'
			},
			
			pause() {
				this.eventCommand = 'pause'
			},
			
			resetFunc() {
				this.renderFunc = {
					name: null,
					params: null
				}
			},
			
			remove(params) {
				this.renderFunc = {
					name: 'removeHandler',
					params
				}
			},
			
			fullScreen(params) {
				this.renderFunc = {
					name: 'fullScreenHandler',
					params
				}
			},
			
			toSeek(sec, isDelay = false) {
				this.renderFunc = {
					name: 'toSeekHandler',
					params: {
						sec,
						isDelay
					}
				}
			},
			
			// 新增：预加载相邻视频
			preloadAdjacentVideos(videoList, currentIndex) {
				if (!this.optimizationConfig.preloadCount) return;
				
				const preloadCount = this.optimizationConfig.preloadCount;
				for (let i = 1; i <= preloadCount; i++) {
					const nextVideo = videoList[currentIndex + i];
					if (nextVideo && nextVideo.src) {
						this.preloadVideo(nextVideo.src);
					}
				}
			},
			
			// 视频预加载
			preloadVideo(videoUrl) {
				// 创建隐藏的视频元素进行预加载
				const preloadVideo = document.createElement('video');
				preloadVideo.src = videoUrl;
				preloadVideo.preload = 'metadata';
				preloadVideo.style.display = 'none';
				document.body.appendChild(preloadVideo);
				
				// 预加载完成后移除
				preloadVideo.addEventListener('loadedmetadata', () => {
					setTimeout(() => {
						document.body.removeChild(preloadVideo);
					}, 1000);
				});
			}
		}
	}
</script>

<script module="domVideoPlayer" lang="renderjs">
	const PLAYER_ID = 'DOM_VIDEO_PLAYER'
	const LOADING_OVERLAY_CLASS = '.custom-loading-overlay'
	const LOADING_HIDDEN_CLASS = 'is-hidden'

	// 内存管理类
	class VideoMemoryManager {
		static clearVideoCache(keepCurrent = true) {
			// 清理视频缓存，保留当前播放视频
			const videos = document.querySelectorAll('video');
			videos.forEach(video => {
				if (keepCurrent && video.src === this.currentVideoSrc) return;
				video.src = '';
				video.load();
			});
		}
		
		static checkMemoryPressure() {
			if (typeof performance !== 'undefined' && performance.memory) {
				const used = performance.memory.usedJSHeapSize;
				const limit = performance.memory.jsHeapSizeLimit;
				return used / limit > 0.7; // 内存使用超过70%
			}
			return false;
		}
	}

	// 快速启动优化
	class QuickStartPlayer {
		static async loadFirstFrame(videoEl, videoUrl) {
			return new Promise((resolve, reject) => {
				try {
					// 使用 range request 只加载视频开头部分
					const xhr = new XMLHttpRequest();
					xhr.open('GET', videoUrl);
					xhr.setRequestHeader('Range', 'bytes=0-65536'); // 前64KB
					xhr.responseType = 'blob';
					
					xhr.onload = function() {
						if (xhr.status === 200 || xhr.status === 206) {
							const blob = xhr.response;
							const url = URL.createObjectURL(blob);
							videoEl.src = url;
							resolve();
						} else {
							reject(new Error('Failed to load first frame'));
						}
					};
					
					xhr.onerror = reject;
					xhr.send();
				} catch (error) {
					reject(error);
				}
			});
		}
	}

	export default {
		data() {
			return {
				num: '',
				videoEl: null,
				loadingEl: null,
				delayFunc: null,
				renderProps: {},
				// 新增性能优化相关
				memoryManager: VideoMemoryManager,
				quickStartPlayer: QuickStartPlayer,
				preloadedVideos: new Map(),
				currentVideoSrc: '',
				networkMonitor: null
			}
		},
		computed: {
			playerId() {
				return `${PLAYER_ID}_${this.num}`
			},
			wrapperId() {
				return `video-wrapper-${this.num}`
			}
		},
		methods: {
			isApple() {
				const ua = navigator.userAgent.toLowerCase()
				return ua.indexOf('iphone') !== -1 || ua.indexOf('ipad') !== -1
			},

			_setupLoadingElement() {
				if (!this.loadingEl) {
					const playerWrapperEl = document.getElementById(this.wrapperId);
					if (playerWrapperEl) {
						this.loadingEl = playerWrapperEl.querySelector(LOADING_OVERLAY_CLASS);
					}
				}
				return this.loadingEl;
			},

			_ensureLoadingState() {
				this._setupLoadingElement();
				if (this.loadingEl) {
					if (this.renderProps.isLoading && !this.isApple()) {
						this.loadingEl.classList.remove(LOADING_HIDDEN_CLASS);
					} else {
						this.loadingEl.classList.add(LOADING_HIDDEN_CLASS);
					}
				}
			},

			_hideLoading() {
				this._setupLoadingElement();
				if (this.loadingEl) {
					this.loadingEl.classList.add(LOADING_HIDDEN_CLASS);
				}
				this.$ownerInstance.callMethod('setViewData', {
					key: 'showLoading',
					value: false
				});
			},

			_showLoading() {
				this._setupLoadingElement();
				if (this.loadingEl) {
					this.loadingEl.classList.remove(LOADING_HIDDEN_CLASS);
				}
				this.$ownerInstance.callMethod('setViewData', {
					key: 'showLoading',
					value: true
				});
			},

			_revealVideo() {
				if (this.videoEl && !this.videoEl.classList.contains('video-visible')) {
					this.videoEl.classList.add('video-visible');
				}
			},

			async initVideoPlayer(src) {
				this.delayFunc = null
				await this.$nextTick()
				this._setupLoadingElement();
				
				// 内存压力检查
				if (this.memoryManager.checkMemoryPressure()) {
					this.memoryManager.clearVideoCache(false);
				}

				if (!src) {
					this._hideLoading();
					if (this.videoEl) {
						this.videoEl.classList.remove('video-visible');
						this.videoEl.src = '';
					}
					return;
				}

				this.currentVideoSrc = src;
				this._ensureLoadingState();

				if (this.videoEl) {
					this.videoEl.classList.remove('video-visible');
					
					// 使用快速启动优化
					if (this.renderProps.optimizationConfig?.preload === 'metadata') {
						this._showLoading();
						try {
							await this.quickStartPlayer.loadFirstFrame(this.videoEl, src);
							this._revealVideo();
							this._hideLoading();
						} catch (error) {
							console.warn('快速启动失败，使用常规加载:', error);
							this.videoEl.src = src;
						}
					} else {
						this.videoEl.src = src;
					}
					return;
				}

				await this.createVideoElement(src);
			},

			async createVideoElement(src) {
				const videoEl = document.createElement('video')
				this.videoEl = videoEl
				this.listenVideoEvent()

				const {
					autoplay,
					muted,
					controls,
					loop,
					playbackRate,
					objectFit,
					poster,
					optimizationConfig,
					preloadStrategy,
					maxBufferSize
				} = this.renderProps
				
				// 应用性能优化配置
				videoEl.src = src
				videoEl.autoplay = optimizationConfig?.autoplay ?? autoplay
				videoEl.controls = controls
				videoEl.loop = loop
				videoEl.muted = muted
				videoEl.playbackRate = playbackRate
				videoEl.id = this.playerId
				videoEl.setAttribute('preload', optimizationConfig?.preload || preloadStrategy || 'auto')
				videoEl.setAttribute('playsinline', true)
				videoEl.setAttribute('webkit-playsinline', true)
				videoEl.setAttribute('crossorigin', 'anonymous')
				videoEl.setAttribute('controlslist', 'nodownload')
				videoEl.setAttribute('disablePictureInPicture', true)
				videoEl.style.objectFit = objectFit
				
				// 设置缓冲区大小
				if (maxBufferSize && videoEl.buffered) {
					videoEl.addEventListener('progress', () => {
						if (videoEl.buffered.length > 0) {
							const bufferedEnd = videoEl.buffered.end(videoEl.buffered.length - 1);
							const currentTime = videoEl.currentTime;
							if (bufferedEnd - currentTime > maxBufferSize) {
								// 暂停加载以避免过度缓冲
								videoEl.pause();
								setTimeout(() => {
									if (!videoEl.paused) videoEl.play();
								}, 1000);
							}
						}
					});
				}
				
				poster && (videoEl.poster = poster)
				videoEl.style.width = '100%'
				videoEl.style.height = '100%'
				videoEl.style.position = 'relative';
				videoEl.style.zIndex = '1';

				const playerWrapper = document.getElementById(this.wrapperId)
				if (playerWrapper) {
					const loadingOverlayRef = playerWrapper.querySelector(LOADING_OVERLAY_CLASS);
					if (loadingOverlayRef) {
						playerWrapper.insertBefore(videoEl, loadingOverlayRef);
					} else {
						playerWrapper.appendChild(videoEl);
					}
				}

				// 快速启动优化
				if (optimizationConfig?.preload === 'metadata' && !autoplay) {
					this._showLoading();
					try {
						await this.quickStartPlayer.loadFirstFrame(videoEl, src);
						this._revealVideo();
						this._hideLoading();
					} catch (error) {
						console.warn('快速启动失败:', error);
						// 回退到正常加载
						videoEl.src = src;
					}
				}
			},

			listenVideoEvent() {
				// 原有的事件监听代码保持不变，增加一些性能监控
				const playHandler = () => {
					this.$ownerInstance.callMethod('eventEmit', {
						event: 'play'
					})
					this.$ownerInstance.callMethod('setViewData', {
						key: 'playing',
						value: true
					})
					this._revealVideo();
					this._hideLoading();
				}
				this.videoEl.addEventListener('play', playHandler)

				const pauseHandler = () => {
					this.$ownerInstance.callMethod('eventEmit', {
						event: 'pause'
					})
					this.$ownerInstance.callMethod('setViewData', {
						key: 'playing',
						value: false
					})
				}
				this.videoEl.addEventListener('pause', pauseHandler)

				const endedHandler = () => {
					this.$ownerInstance.callMethod('eventEmit', {
						event: 'ended'
					})
					this.$ownerInstance.callMethod('resetEventCommand')
				}
				this.videoEl.addEventListener('ended', endedHandler)

				const canPlayHandler = () => {
					this.$ownerInstance.callMethod('eventEmit', {
						event: 'canplay'
					})
					this.execDelayFunc()
				}
				this.videoEl.addEventListener('canplay', canPlayHandler)

				const errorHandler = (e) => {
					if (this.renderProps.isLoading && !this.isApple() && this.loadingEl) {
						this.loadingEl.classList.remove(LOADING_HIDDEN_CLASS);
					}
					this.$ownerInstance.callMethod('eventEmit', {
						event: 'error',
						data: e
					})
				}
				this.videoEl.addEventListener('error', errorHandler)

				const loadedMetadataHandler = () => {
					this.$ownerInstance.callMethod('eventEmit', {
						event: 'loadedmetadata'
					})
					const duration = this.videoEl.duration
					this.$ownerInstance.callMethod('eventEmit', {
						event: 'durationchange',
						data: duration
					})
					this.$ownerInstance.callMethod('setViewData', {
						key: 'duration',
						value: duration
					})
					if (!this.renderProps.autoplay || this.isApple()) {
						this.loadFirstFrame();
					}
				}
				this.videoEl.addEventListener('loadedmetadata', loadedMetadataHandler)

				const timeupdateHandler = (e) => {
					const currentTime = e.target.currentTime
					this.$ownerInstance.callMethod('eventEmit', {
						event: 'timeupdate',
						data: currentTime
					})
					this.$ownerInstance.callMethod('setViewData', {
						key: 'currentTime',
						value: currentTime
					})
				}
				this.videoEl.addEventListener('timeupdate', timeupdateHandler)

				const ratechangeHandler = (e) => {
					const playbackRate = e.target.playbackRate
					this.$ownerInstance.callMethod('eventEmit', {
						event: 'ratechange',
						data: playbackRate
					})
				}
				this.videoEl.addEventListener('ratechange', ratechangeHandler)

				// 性能监控：缓冲事件
				const progressHandler = () => {
					if (this.videoEl.buffered.length > 0) {
						const bufferedEnd = this.videoEl.buffered.end(this.videoEl.buffered.length - 1);
						const currentTime = this.videoEl.currentTime;
						const bufferedTime = bufferedEnd - currentTime;
						
						this.$ownerInstance.callMethod('eventEmit', {
							event: 'buffering',
							data: {
								bufferedTime,
								currentTime,
								bufferedEnd
							}
						});
					}
				}
				this.videoEl.addEventListener('progress', progressHandler);

				if (this.isApple()) {
					this.videoEl.addEventListener('webkitpresentationmodechanged', () => {
						const isFullScreen = this.videoEl.webkitPresentationMode === 'fullscreen'
						this.$ownerInstance.callMethod('eventEmit', {
							event: 'fullscreenchange',
							data: isFullScreen
						})
					})
				} else {
					const fullscreenchangeHandler = () => {
						let isFullScreen = !!(document.fullscreenElement || document.webkitFullscreenElement);
						this.$ownerInstance.callMethod('eventEmit', {
							event: 'fullscreenchange',
							data: isFullScreen
						})
					}
					this.videoEl.addEventListener('fullscreenchange', fullscreenchangeHandler);
					this.videoEl.addEventListener('webkitfullscreenchange', fullscreenchangeHandler);
					document.addEventListener('fullscreenchange', fullscreenchangeHandler);
					document.addEventListener('webkitfullscreenchange', fullscreenchangeHandler);
				}
			},

			// 优化后的 loadFirstFrame 方法
			loadFirstFrame() {
				if (!this.videoEl) return;
				let {
					autoplay,
					muted
				} = this.renderProps;

				const revealAndHideLoading = () => {
					this._revealVideo();
					this._hideLoading();
				};

				// 根据设备性能等级调整策略
				const optimizationConfig = this.renderProps.optimizationConfig || {};
				
				if (this.isApple()) {
					const playPromise = this.videoEl.play();
					if (playPromise !== undefined) {
						playPromise.then(() => {
							if (!autoplay) {
								this.videoEl.pause();
								revealAndHideLoading();
							}
						}).catch(err => {
							this._hideLoading();
						});
					} else {
						this.videoEl.play();
						if (!autoplay) {
							this.videoEl.pause();
							revealAndHideLoading();
						}
					}
				} else {
					if (!autoplay) {
						// 低端设备使用更保守的策略
						if (optimizationConfig.disableVisualEffects) {
							this.videoEl.muted = true;
							setTimeout(() => {
								const playPromise = this.videoEl.play();
								if (playPromise !== undefined) {
									playPromise.then(() => {
										setTimeout(() => {
											this.videoEl.pause();
											this.videoEl.muted = muted;
											revealAndHideLoading();
										}, 30); // 低端设备缩短等待时间
									}).catch(error => {
										this.videoEl.muted = muted;
										revealAndHideLoading();
									});
								}
							}, 5);
						} else {
							// 中高端设备使用原有策略
							this.videoEl.muted = true;
							setTimeout(() => {
								const playPromise = this.videoEl.play();
								if (playPromise !== undefined) {
									playPromise.then(() => {
										setTimeout(() => {
											this.videoEl.pause();
											this.videoEl.muted = muted;
											revealAndHideLoading();
										}, 50);
									}).catch(error => {
										this.videoEl.muted = muted;
										revealAndHideLoading();
									});
								}
							}, 10);
						}
					}
				}
			},

			triggerCommand(eventType) {
				if (eventType && this.videoEl) {
					this.$ownerInstance.callMethod('resetEventCommand')
					if (typeof this.videoEl[eventType] === 'function') {
						const promise = this.videoEl[eventType]();
						if (promise && typeof promise.catch === 'function') {
							promise.catch(error => {
								console.warn(`Video ${eventType} error:`, error);
							});
						}
					}
				}
			},
			
			triggerFunc(func) {
				const {
					name,
					params
				} = func || {}
				if (name && typeof this[name] === 'function') {
					this[name](params)
					this.$ownerInstance.callMethod('resetFunc')
				}
			},
			
			removeHandler() {
				if (this.videoEl) {
					this.videoEl.pause()
					this.videoEl.src = ''
					this.videoEl.classList.remove('video-visible');
					this.$ownerInstance.callMethod('setViewData', {
						key: 'videoSrc',
						value: ''
					})
				}
				this._hideLoading();
				// 清理内存
				this.memoryManager.clearVideoCache(false);
			},
			
			fullScreenHandler() {
				if (this.videoEl) {
					if (this.isApple()) {
						this.videoEl.webkitEnterFullscreen && this.videoEl.webkitEnterFullscreen()
					} else {
						if (this.videoEl.requestFullscreen) this.videoEl.requestFullscreen();
						else if (this.videoEl.webkitRequestFullscreen) this.videoEl.webkitRequestFullscreen();
						else if (this.videoEl.msRequestFullscreen) this.videoEl.msRequestFullscreen();
					}
				}
			},
			
			toSeekHandler({
				sec,
				isDelay
			}) {
				const func = () => {
					if (this.videoEl && sec >= 0 && sec <= this.videoEl.duration) {
						this.videoEl.currentTime = sec
					}
				}
				if (isDelay) {
					this.delayFunc = func
				} else {
					if (this.videoEl && this.videoEl.readyState >= 1) func();
					else this.delayFunc = func;
				}
			},
			
			execDelayFunc() {
				if (this.delayFunc && typeof this.delayFunc === 'function') {
					this.delayFunc()
					this.delayFunc = null
				}
			},
			
			viewportChange(newProps, oldProps) {
				this.renderProps = newProps || {};
				const {
					autoplay,
					muted,
					controls,
					loop,
					playbackRate,
					objectFit,
					poster,
					optimizationConfig
				} = newProps || {};

				if (this.videoEl) {
					if (!oldProps || newProps.autoplay !== oldProps.autoplay) this.videoEl.autoplay = autoplay;
					if (!oldProps || newProps.controls !== oldProps.controls) this.videoEl.controls = controls;
					if (!oldProps || newProps.loop !== oldProps.loop) this.videoEl.loop = loop;
					if (!oldProps || newProps.muted !== oldProps.muted) this.videoEl.muted = muted;
					if (!oldProps || newProps.playbackRate !== oldProps.playbackRate) this.videoEl.playbackRate = playbackRate;
					if (!oldProps || newProps.objectFit !== oldProps.objectFit) this.videoEl.style.objectFit = objectFit;
					if (!oldProps || newProps.poster !== oldProps.poster) this.videoEl.poster = poster;
					
					// 应用性能优化配置
					if (optimizationConfig?.preload) {
						this.videoEl.preload = optimizationConfig.preload;
					}
				}

				this._ensureLoadingState();
			},
			
			randomNumChange(val) {
				this.num = val
			}
		}
	}
</script>

<style scoped>
	.player-wrapper {
		overflow: hidden;
		width: 100%;
		height: 100%;
		padding: 0;
		position: relative;
		background-color: #000;
	}

	::v-deep .player-wrapper video {
		opacity: 0;
		transition: opacity 0.3s ease-in-out; /* 减少过渡时间 */
		display: block;
		width: 100%;
		height: 100%;
	}

	::v-deep .player-wrapper video.video-visible {
		opacity: 1;
	}

	.custom-loading-overlay {
		position: absolute;
		top: 0;
		left: 0;
		z-index: 10;
		width: 100%;
		height: 100%;
		background-color: #f8f8f8;
		display: flex;
		align-items: center;
		justify-content: center;
		opacity: 1;
		pointer-events: auto;
		transition: opacity 0.2s ease-out; /* 加快过渡 */
	}

	.custom-loading-overlay.is-hidden {
		opacity: 0;
		pointer-events: none;
	}

	.custom-loading-spinner {
		width: 30px;
		height: 30px;
		border: 2px solid #adadad;
		border-top-color: #e0e0e0;
		border-right-color: #e0e0e0;
		border-bottom-color: #e0e0e0;
		border-radius: 100%;
		animation: dom-video-player-circle-spin 0.6s linear infinite; /* 加快动画 */
	}

	@keyframes dom-video-player-circle-spin {
		0% {
			transform: rotate(0);
		}
		100% {
			transform: rotate(360deg);
		}
	}
</style>